package Controller;

import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Date;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import View.ModifieContactView;

/**
 * Action Listener for the ModifieContact JDialog
 * @author adrien
 *
 */


public class ModifieContactListener implements ActionListener{

	private ModifieContactView view;
	private AddressBookController controller;
	public static final String NOTHING ="";	
	public static final String SPACE =" ";
	public static final String RESOURCES_FOLDER ="resources/";
	public static final String ERROR_MESSAGE = "The name tapped is not correct or already used";
	public static final String ERROR_IMG = "The selected file is not an image";
	public static final String JPEG_EXTENSION = ".jpeg";
	public static final String JPG_EXTENSION = ".jpg";
	public static final String PNG_EXTENSION = ".png";
	public static final String BMP_EXTENSION = ".bmp";
	public static final String SPACE_ENCODED = "%20";
	public static final String SPACE_CHAR = " ";
	public static final String FILE_BEGINING = "file:/" ;
	public static final String CANCEL ="Cancel";
	public static final String OK = "OK";
	public static final String SLASH = "/";
	public static final String POINT_CHAR = ".";
	
	private String filePath=null,extension=null,copyFilePath=null,fileName=null,oldFileName,deletePath;
	private StringBuilder copyFilePathSB,imageNameSB,deletePathSB;
	private boolean imgChanged=false;
	
	public ModifieContactListener (ModifieContactView view, AddressBookController controller){
		this.view = view;
		this.controller=controller;
	}
	
	public AddressBookController getController(){
		return controller;
	}
	
	/**
	 * if there is no change for the first name and last name we validate
	 * If there is a change : The First name and last name are correct if their are not empty and if there is no space in it
	 * and if a contact with this name doesn't already exist 
	 * 
	 * @return true if first name and last name are tapped correctly else return false 
	 */
	
	public boolean isTappingCorrect (){
		if (controller.getContact().getFirstName().equals(view.getTfFirstName()) || controller.getContact().getLastName().equals(view.getTfLastName())) {
			return true; // if we haven't changed the name
		}
		else {
			if(view.getTfFirstName().equals(NOTHING) || view.getTfFirstName().contains(SPACE)|| view.getTfLastName().equals(NOTHING)|| view.getTfLastName().contains(SPACE) || controller.isContactExist(view.getTfFirstName(), view.getTfLastName())) {
				return false;
			}else return true;
		}
	}
	
	
	
	
	@Override
	public void actionPerformed(ActionEvent e) {
		
		
		
		if (e.getActionCommand().equals(OK)) {
			if (isTappingCorrect()){
				oldFileName = controller.getContact().getImgURL();
				controller.deleteContactAction(controller.getContact());
				
				
				if (imgChanged==false){
					controller.addContactAction(view.getTfFirstName(),view.getTfLastName(),view.getTfGroup(),view.getTfHomeAddress(),view.getTfCompanyName(),view.getTfCompanyAddress(),view.getTfPersPhone(),view.getTfProPhone(),view.getTfWebSite(),view.getTfEmail(),view.getTfBirthDate(),oldFileName,new Date());
				}else {
					controller.addContactAction(view.getTfFirstName(),view.getTfLastName(),view.getTfGroup(),view.getTfHomeAddress(),view.getTfCompanyName(),view.getTfCompanyAddress(),view.getTfPersPhone(),view.getTfProPhone(),view.getTfWebSite(),view.getTfEmail(),view.getTfBirthDate(),fileName,new Date());
					
					deletePathSB = new StringBuilder();
					deletePathSB.append(view.getClass().getResource(RESOURCES_FOLDER)).append(oldFileName);
					deletePath = deletePathSB.toString();
	            	String deletePathSplit []=deletePath.split(FILE_BEGINING);
	            	deletePath = deletePathSplit[1];
	            	deletePath=deletePath.replace(SPACE_ENCODED, SPACE_CHAR);
	            	
	            	/*if (new File(deletePath).exists()) {
	            		
	            		try {
							Files.delete(Paths.get(deletePath));
		            	} catch (IOException e1) {
		            		e1.printStackTrace();
		            	}
	            	}*/
	            	
	            	
	            	
	            	try {
						Files.copy(Paths.get(filePath), Paths.get(copyFilePath), REPLACE_EXISTING);
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
	            	
	            	
	            	
					
					
					
				}

				view.dispose();
			}else {
				JOptionPane.showMessageDialog(null,ERROR_MESSAGE);
			}
			
		}
		if (e.getActionCommand().equals(CANCEL)) {
			view.dispose();
		}
		
		if (e.getActionCommand().equals(controller.getContact().getImgURL())) {
			
			//Create a file chooser
			final JFileChooser fc = new JFileChooser();
			int returnVal = fc.showOpenDialog(view);
			System.out.println("CouCOU");
			
			
			if (returnVal == JFileChooser.APPROVE_OPTION) {
	            
				if (isTappingCorrect()){
					filePath=fc.getSelectedFile().getAbsolutePath();
		            extension = filePath.substring(filePath.lastIndexOf(POINT_CHAR));
		            //fileName = filePath.substring(filePath.lastIndexOf("/"));
		            
		            if (extension.equals(JPEG_EXTENSION) || extension.equals(JPG_EXTENSION) || extension.equals(PNG_EXTENSION) || extension.equals(BMP_EXTENSION)){
		            
		            	copyFilePathSB = new StringBuilder();
		            	copyFilePathSB.append(view.getClass().getResource(RESOURCES_FOLDER)).append(view.getTfFirstName()).append(view.getTfLastName()).append(extension);
		            	copyFilePath = copyFilePathSB.toString();
		            	String copyFilePathSplit []=copyFilePath.split(FILE_BEGINING);
		            	copyFilePath = copyFilePathSplit[1];
		            	copyFilePath=copyFilePath.replace(SPACE_ENCODED, SPACE_CHAR);
		            	fileName = copyFilePath.substring(copyFilePath.lastIndexOf(SLASH) + 1);
		            	System.out.println(fileName);
		            	System.out.println(filePath);
		            	System.out.println(extension);
		            	System.out.println(copyFilePath);
		            	
		            	imageNameSB = new StringBuilder();
		            	imageNameSB.append(view.getTfFirstName()).append(view.getTfLastName());
		            	view.setImageName(filePath);
		            	
				        imgChanged=true;

		            }else {
		            	JOptionPane.showMessageDialog(null,ERROR_IMG);
		            }
				
	            
			}else {
            	JOptionPane.showMessageDialog(null,ERROR_MESSAGE);
            }
			
			
		}
		
		
		
	}
		
}
}
